<?php

namespace app\goods\controller;

use cmf\controller\AdminBaseController;
use app\goods\model\GoodsAttributeModel;
use exchange\Exchange;
use think\Db;

class AdminGoodsAttributeController extends AdminBaseController 
{

    function _initialize() {
        parent::_initialize();
        $this->goodsAttrModel = new GoodsAttributeModel();

        //实例化，参数解析(数据库表名,数据表主键字段名,数据表重要段名)
        $this->exc = new Exchange($this->goodsAttrModel, 'attr_id', 'attr_name');

        $this->goods_type = $this->request->param('goods_type', 0, 'intval');
        $this->assign('goods_type',$this->goods_type);

        $this->assign('lang',lang(''));
    }

    // 后台产品属性列表
    public function index(){
        /* 查询条件 */
        $filter               = $this->request->param();
        $filter['sort_by']    = $this->request->param('sort_by','attr_id','trim');
        $filter['list_order'] = $this->request->param('list_order','DESC','trim');

        $data = $this->goodsAttrModel->adminGoodsAttrList($filter);

        $data->appends($filter);

        // 产品类型列表
        $goods_type_list = goods_type_list($this->goods_type);

        //当前排序依据
        $sort_flag  = sort_flag($filter);
        $this->assign($sort_flag['tag'], $sort_flag['img']);

        //查询条件
        $this->assign('list', $data->items());
        $this->assign('page', $data->render());
        $this->assign('goods_type_list', $goods_type_list);
        $this->assign('filter', $filter);

        return $this->fetch();
    }

    // 产品属性添加
    public function add(){
        // 产品类型列表
        $goods_type_list = goods_type_list($this->goods_type);

        $this->assign('goods_type_list', $goods_type_list);

        return $this->fetch();
    }

    // 产品属性添加提交
    public function addPost(){
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];
            $result = $this->validate($post, 'AdminGoodsAttribute');
            if ($result !== true) {
                $this->error($result);
            }

            /* 检查属性名称是否重复 */
            $attr_id   = $this->request->param('attr_id',0,'intval');
            $attr_name = $this->request->param('attr_name','','trim');
            $cat_id    = $this->request->param('cat_id',0,'intval');
            if (!$this->exc->is_only('attr_name', $attr_name, $attr_id, " cat_id = $cat_id")) {
                $this->error(lang('name_exist'));
            }

            /*若属性值为手工录入，则清空可选值列表*/
            $attr_input_type = $post['attr_input_type'];
            if( $attr_input_type > 0 ) {
                if( empty( $post['attr_values'] ) ){
                    $this->error("请输入该属性的可选值！");
                }
            }else {
                $post['attr_values'] = '';
            }

            //站点ID
            $post['site_id'] = get_site_id();
            
            $res = $this->goodsAttrModel->insertGetId($post);

            if( $res ){
                //操作日志
                admin_log('', 'add', 'goods_attr');
                
                $this->success('添加成功!', url('AdminGoodsAttribute/edit', ['attr_id' => $res]));
            }else{
                $this->error("添加失败！");
            }
        }
    }

    // 产品属性编辑
    public function edit(){
        $attr_id = $this->request->param('attr_id',0,'intval');
        $data    = $this->goodsAttrModel->where(array("attr_id" => $attr_id))->find();

        // 产品类型列表
        $goods_type      = $data['cat_id'];
        $goods_type_list = goods_type_list($goods_type);

        $this->assign('goods_type',$goods_type);
        $this->assign('goods_type_list', $goods_type_list);
        $this->assign("data",$data);

        return $this->fetch();
    }

    // 产品属性编辑提交
    public function editPost(){
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];
            $result = $this->validate($post, 'AdminGoodsAttribute');
            if ($result !== true) {
                $this->error($result);
            }

            /* 检查属性名称是否重复 */
            $attr_id   = $this->request->param('attr_id',0,'intval');
            $attr_name = $this->request->param('attr_name','','trim');
            $cat_id    = $this->request->param('cat_id',0,'intval');
            if (!$this->exc->is_only('attr_name', $attr_name, $attr_id, " cat_id = $cat_id")) {
                $this->error(lang('name_exist'));
            }

            /*若属性值为手工录入，则清空可选值列表*/
            $attr_input_type = $post['attr_input_type'];
            if( $attr_input_type > 0 ) {
                if( empty( $post['attr_values'] ) ){
                    $this->error("请输入该属性的可选值！");
                }
            }else {
                $post['attr_values'] = '';
            }
            

            $res = $this->goodsAttrModel->update($post);

            if( $res ){
                //操作日志
                admin_log('', 'edit', 'goods_attr');

                $this->success('修改成功！');
            }else{
                $this->error("修改失败！");
            }
        }
    }

    // 获取某属性商品数量
    public function getAttrNum(){
        $attr_id   = $this->request->param('attr_id',0,'intval');
        $goods_num = db()
                  -> table('__GOODS_ATTR__ a,__GOODS__ g')
                  -> where("g.goods_id = a.goods_id AND g.post_status <>3 AND attr_id = '$attr_id'")
                  -> count();
        
        if ($goods_num > 0) {
            $drop_confirm = sprintf(lang('notice_drop_confirm'), $goods_num);
        } else {
            $drop_confirm = lang('drop_confirm');
        }
        
        $this->success($drop_confirm);
    }

    // 删除产品属性
    public function delete() {
        $attr_id = $this->request->param('attr_id',0,'intval');
        if( !empty($attr_id) ){
            $res = $this->goodsAttrModel->where('attr_id', $attr_id)->delete();
            if( $res !== false ){
                db('goods_attr')->where('attr_id', $attr_id)->delete();

                //操作日志
                admin_log('', 'delete', 'goods_attr');

                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }

        $ids = $this->request->param('ids/a');
        if( !empty($ids) ){
            $res = $this->goodsAttrModel->where('attr_id', 'in', $ids)->delete();
            if ( $res !== false ) {
                db('goods_attr')->where('attr_id', 'in', $ids)->delete();

                //操作日志
                admin_log('', 'batch_delete', 'goods_attr');

                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }

        
    }


    // 产品属性排序
    public function listOrder() {
        parent::listOrders(Db::name('goods_attribute'));
        $this->success("排序更新成功！", '');
    }

    // // 编辑属性名称
    // public function edit_attr_name() {
    //     $id  = I('post.id',0,'intval');
    //     $val = I('post.val','','trim');
        
    //     /* 取得该属性所属商品类型id */
    //     $cat_id = $this->exc->get_name($id, 'cat_id');

    //     /* 检查属性名称是否重复 */
    //     if (!$this->exc->is_only('attr_name', $val, $id, " cat_id = '$cat_id'")) {
    //         make_json_error( L('name_exist') );
    //     }

    //     $this->exc->edit("attr_name='$val'", $id);

    //     make_json_result(stripslashes($val));
    // }

}
